package com.wanmait.wanmarecruit.webController;

import com.wanmait.wanmarecruit.entity.JobOrientation;
import com.wanmait.wanmarecruit.entity.User;
import com.wanmait.wanmarecruit.service.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.util.UUID;

@Controller
@RequestMapping("web")
public class WebSignUpController {

    @Resource
    private UserService userService;
    @Resource
    private EducationService educationService;
    @Resource
    private ProvinceService provinceService;
    @Resource
    private PositionTypeService positionTypeService;
    @Resource
    private SalaryService salaryService;
    @Resource
    private JobOrientationService jobOrientationService;

    @Value("${hash.algorithm-name}")
    private String hashName;
    @Value("${hash.iterations}")
    private int hashIterations;
    //注册用户
    @RequestMapping("signUpUser")
    public String signUpUser(User user){
        user.setEnable(false);
        String salt = UUID.randomUUID().toString().replaceAll("-","");
        SimpleHash simpleHash = new SimpleHash(hashName,user.getPass(),salt,hashIterations);
        user.setSalt(salt);
        user.setPass(simpleHash.toString());
        userService.save(user);
        return "redirect:/web/signUpUserInfo/"+user.getId();
    }

    @RequestMapping("/signUpUserInfo/{id}")
    public ModelAndView signUpUserInfo(@PathVariable("id") Integer id)
    {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/web/personal/signUpUserInfo");
        modelAndView.addObject("educations",educationService.getAllEducation());
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    //验证注册用户是否重复
    @RequestMapping("signUpVerify")
    @ResponseBody
    public String signUpVerify(String phone){
        boolean flag = userService.signUpVerify(phone);
        if(!flag){
            return "false";
        }
        else {
            return "true";
        }
    }

    //验证码不区分大小写
    @RequestMapping("verifyVerifyCode")
    @ResponseBody
    public String verifyVerifyCode(HttpSession session,String verifyCode){
        String code = (String)session.getAttribute("code");
        return code.equalsIgnoreCase(verifyCode)+"";
    }

    //生成随机验证码
    @RequestMapping("verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response){
        String code = "";
        Random random = new Random();
        for (int i=0;i<4;i++){
            int ranNum =  random.nextInt(123);
            if((ranNum>=48&&ranNum<=57)||(ranNum>=97&&ranNum<=122)||(ranNum>=65&&ranNum<=90)){
                code = code+(char)ranNum;
            }
            else {
                i--;
            }
        }
        HttpSession session = request.getSession();
        session.setAttribute("code", code);//获得session对象，将验证码存入session

        BufferedImage image = new BufferedImage(99,45,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        //背景颜色
        graphics.setColor(Color.white);
        //白色填充矩形
        graphics.fillRect(0,0,100,50);
        //画笔颜色
        graphics.setColor(new Color(0,0,0));
        //文本字体，随机字体大小
        graphics.setFont(new Font("仿宋",Font.BOLD,25+random.nextInt(10)));
        //绘制验证码
        graphics.drawString(code, 25, 30);
        //绘制干扰线
        for (int i=0;i<10;i++){
            graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            int x1 = random.nextInt(image.getWidth());
            int y1 = random.nextInt(image.getHeight());
            int x2 = random.nextInt(image.getWidth());
            int y2 = random.nextInt(image.getHeight());
            graphics.drawLine(x1,y1,x2,y2);
        }

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/signUpUserInformation")
    public String signUpUserInformation(User user)
    {
        if (user.getSex().equals("男"))
        {
            user.setFace("customer-2.png");
        }
        else {
            user.setFace("customer-3.png");
        }
        userService.updateUserNotEnable(user);
        return "redirect:/web/personal/signUpExp/"+user.getId();
    }

    @RequestMapping("/personal/signUpExp/{id}")
    public ModelAndView signUpExp(@PathVariable("id")Integer id)
    {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/web/personal/signUpExp");
        modelAndView.addObject("id",id);
        modelAndView.addObject("provinces",provinceService.getProvincesBySort());
        modelAndView.addObject("positionTypes",positionTypeService.getAllPositionType());
        modelAndView.addObject("salaries",salaryService.getAllSalary());
        return modelAndView;
    }

    @PostMapping("/signUpExpInfo")
    public String signUpExpInfo(JobOrientation jobOrientation)
    {
        jobOrientationService.save(jobOrientation);
        userService.updateEnableTrueByUserId(jobOrientation.getUserId());
        return "redirect:/web/personal/signIn?userId="+jobOrientation.getUserId();
    }
}
